package com.fancon.android.gardenjokesx.activity;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import net.arnx.jsonic.JSON;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListView;

import com.fancon.android.emoji.widget.RichTextView;
import com.fancon.android.gardenjokesx.GardenJokesBaseActivity;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.entity.Comment;
import com.fancon.android.gardenjokesx.entity.Photo;
import com.fancon.android.gardenjokesx.entity.User;
import com.fancon.android.gardenjokesx.rpc.GardenJokesApiConnect;
import com.fancon.android.gardenjokesx.rpc.JsonPaser;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.gardenjokesx.utils.GlobalDelegate;
import com.fancon.android.gardenjokesx.utils.StringUtil;
import com.fancon.android.gardenjokesx.utils.TimeUtil;
import com.fancon.android.gardenjokesx.utils.UserUtil;
import com.fancon.android.gardenjokesx.widget.DetailTopControlView;
import com.fancon.android.gardenjokesx.widget.IGlobalStorage;
import com.fancon.android.gardenjokesx.widget.JokeDetailHeader;
import com.fancon.android.multithread.RequestUI;

public class DetailJokesActivity extends GardenJokesBaseActivity {
	private int index = 1;
	private View footerView;
	private ListView commentList;
	private Boolean isFirst = true;
	private Boolean isReload = false;
	private boolean loadingMore = false;
	private ArrayList<Comment> listComments = new ArrayList<Comment>();
	private Boolean isEnd = false;
	private CommentAdapter adapter = null;
	private Photo photo;
	private String currentUser;
	private Boolean isPush = false;
	private DetailTopControlView topControl;
	private JokeDetailHeader header;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.jokes_detail);
		if (getIntent().getExtras() != null) {
			if (getIntent().getExtras().getString(Constant.PHOTO_ID) == null) {
				String photoString = getIntent().getExtras().getString("photo");
				photo = JSON.decode(photoString, Photo.class);
			} else {
				photo = new Photo();
				photo.setPhoto_id(getIntent().getExtras().getString(
						Constant.PHOTO_ID));
			}
			if (getIntent().getExtras().getInt(Constant.SCREEN_ID) == Constant.PUSH_RECEIVE) {
				isPush = true;
				photo.setPhoto_id(getIntent().getExtras().getString(
						Constant.PHOTO_ID));
			}
		}
		User user = UserUtil.getInfoUserLogin(getApplicationContext());
		currentUser = user.getUser_id();
		LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		header = new JokeDetailHeader(this);
		topControl = (DetailTopControlView) findViewById(R.id.joke_detail_control);
		topControl.setHeader(header);
		header.setTopControl(topControl);
		if (!isPush) {
			topControl.setPhoto(photo);
			header.loadContent(photo);
		} else {
			LoadPhotoDetail photoDetailReq = new LoadPhotoDetail(
					"photo_deteil_rq", this);
			getGlobalState().getRequestQueue().addRequest(photoDetailReq);
		}

		commentList = (ListView) findViewById(R.id.lst_id);

		footerView = layoutInflater.inflate(R.layout.listfooter, null, false);
		commentList.addFooterView(footerView);

		commentList.setCacheColorHint(0);
		commentList.addHeaderView(header);
		commentList.setOnScrollListener(new OnScrollListener() {

			// useless here, skip!
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			}

			// dumdumdum
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {

				// what is the bottom iten that is visible
				int lastInScreen = firstVisibleItem + visibleItemCount;

				// is the bottom item visible & not loading more already ? Load
				// more !
				if ((lastInScreen == totalItemCount) && !(loadingMore)
						&& (!isEnd) && (!isFirst)) {
					loadMore();
				}
			}
		});
		// load empty data
		adapter = new CommentAdapter(this);
		commentList.setAdapter(adapter);
		load();
	}

	public void loadMore() {
		footerView.setVisibility(View.VISIBLE);
		index++;
		load();
	}

	public void load() {
		CommentsRequest photoReq = new CommentsRequest("photo_rq", this);
		getGlobalState().getRequestQueue().addRequest(photoReq);
	}

	private void loadDataView() {
		if (adapter == null || isReload) {
			adapter = new CommentAdapter(this);
			commentList.setAdapter(adapter);
			isReload = false;
		} else {
			adapter.notifyDataSetChanged();
		}
	}

	class CommentsRequest extends RequestUI {
		private Activity context;
		// private FanconProgressBar progress;
		private ArrayList<Comment> tmp;

		public CommentsRequest(Object key, Activity activity) {
			super(key, activity);
			// TODO Auto-generated constructor stub
			loadingMore = true;
			context = activity;
			if (isFirst) {
				// progress = FanconProgressBar.show(context,
				// context.getString(R.string.loading));
				showProgress(context.getString(R.string.loading));
			}

		}

		@Override
		public void execute() throws Exception {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("user_id", currentUser));
			nameValuePairs.add(new BasicNameValuePair("photo_id", photo
					.getPhoto_id()));
			nameValuePairs.add(new BasicNameValuePair("page_index", String
					.valueOf(index)));
			GardenJokesApiConnect api = new GardenJokesApiConnect(context);
			String result = api.execGet(getApplicationContext(),
					GardenJokesApiConnect.GROUP_M, "getCommentOfPhoto",
					nameValuePairs);
			Log.d("list comment", result);
			JsonPaser json = new JsonPaser();
			tmp = json.getCommentOfPhoto(result);
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			footerView.setVisibility(View.GONE);

			// if (progress != null) {
			// progress.dismiss();
			// }
			dismissProgress();
			try {
				if (tmp.size() > 0) {
					if (listComments.size() > 0 && !isFirst && !isReload) {
						listComments.addAll(tmp);
					} else {
						listComments = tmp;
					}
				}
				if (tmp.size() == 0) {
					isEnd = true;
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
				isEnd = true;
			}
			loadDataView();
			loadingMore = false;
			isFirst = false;
		}

	}

	class CommentAdapter extends BaseAdapter implements Filterable {
		private LayoutInflater mInflater;
		private Context context;

		public CommentAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
			this.context = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			int ret = listComments.size();
			return ret;
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int arg0, View convertView, ViewGroup arg2) {
			// TODO Auto-generated method stub
			ViewHolder holder;
			final Comment comment = listComments.get(arg0);
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.comment_layout, null);
				holder = new ViewHolder();
				holder.comment = (RichTextView) convertView
						.findViewById(R.id.comment);
				holder.userx = (RichTextView) convertView
						.findViewById(R.id.userx);
				holder.reply = (Button) convertView
						.findViewById(R.id.cm_listusercomment_btnReply);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			try {
				String userTimeStr = context
						.getString(R.string.user_time_comment);
				final String displayUserComment = StringUtil.getDisplayName(
						comment.getFirst_name(), comment.getLast_name(),
						comment.getUser_name());
				final String timeStr = TimeUtil.getTimeCount(
						comment.getTime_post(), context);
				final String displayUserPost = String.format(userTimeStr,
						displayUserComment, timeStr);
				holder.userx.setText(displayUserPost);
				holder.comment.setText(URLDecoder.decode(comment.getContent(),
						"UTF-8"));
				holder.userx.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(context,
								ProfileActivity.class);
						intent.putExtra(Constant.USER_ID_VIEW,
								comment.getUser_id());
						context.startActivity(intent);
					}
				});
				holder.reply.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						Intent intent = new Intent(context, M05Activity.class);
						intent.putExtra(Constant.USER_ID_VIEW,
								comment.getUser_id());
						intent.putExtra(Constant.PHOTO_ID, photo.getPhoto_id());
						intent.putExtra("viewed_user_id", photo.getUser()
								.getUser_id());
						intent.putExtra("reply_user", displayUserComment);
						try {
							ArrayList<Comment> tmp = new ArrayList<Comment>();
							if (listComments.size() < 31) {
								tmp = listComments;
							} else {
								tmp = (ArrayList<Comment>) listComments
										.subList(0, 29);
							}
							intent.putExtra("listComment", JSON.encode(tmp));
						} catch (Exception e) {
							e.printStackTrace();
							// TODO: handle exception
						}
						context.startActivity(intent);
					}
				});
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			return convertView;
		}

		@Override
		public Filter getFilter() {
			// TODO Auto-generated method stub
			return null;
		}

		class ViewHolder {
			RichTextView comment;
			RichTextView userx;
			Button reply;
		}
	}

	public void finishCurrentActivity() {
		this.finish();
	}

	class LoadPhotoDetail extends RequestUI {
		private Context mContext;

		public LoadPhotoDetail(Object key, Activity activity) {
			super(key, activity);
			// TODO Auto-generated constructor stub
			this.mContext = activity;
		}

		@Override
		public void execute() throws Exception {
			// TODO Auto-generated method stub
			List<NameValuePair> requestphotoDetail = new ArrayList<NameValuePair>(
					2);
			requestphotoDetail.add(new BasicNameValuePair("photo_id", photo
					.getPhoto_id()));
			requestphotoDetail.add(new BasicNameValuePair("user_id",
					currentUser));
			try {
				GardenJokesApiConnect api = new GardenJokesApiConnect(mContext);
				String request = api.execGet(getApplicationContext(),
						GardenJokesApiConnect.GROUP_M, "getPhotoDetail",
						requestphotoDetail);
				JsonPaser jP = new JsonPaser();
				photo = jP.getPhotoDetail(request);
				Log.d("load photo detail ID", photo.getPhoto_id());
				Log.d("load photo detail result", request);
			} catch (Exception e) {
				Log.e("Detail jokes",
						"LoadPhotoDetail error: " + e.getMessage());
			}
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			topControl.setPhoto(photo);
			header.loadContent(photo);
		}

	}

	@Override
	public void onResume() {
		super.onResume();
		try {
			if (((IGlobalStorage) getApplication()).isChange()&&!isFirst) {
				photo = ((IGlobalStorage) getApplication()).getCurrentPhoto();
				topControl.setPhoto(photo);
				header.loadContent(photo);
				if (GlobalDelegate.isRFM031) {
					Log.d("refreshingnnnnnnnnnnnn !", "refreshingnnnnnnnnnnnn");
					index = 1;
					loadingMore = false;
					isEnd = false;
					isReload = true;
					load();
					GlobalDelegate.isRFM031 = false;
					GlobalDelegate.isRFM04 = true;
				}
				//((IGlobalStorage) getApplication()).setChange(false);
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public ArrayList<Comment> getListComments() {
		return listComments;
	}

	public void setListComments(ArrayList<Comment> listComments) {
		this.listComments = listComments;
	}

}
